#!/bin/bash
set -e
script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
source "$script_dir/functions"
source "$script_dir/set-config.update-responses"

check_torbrowser_version_var

update_responses_tar_filename="update-responses-$tbb_version_type-$tbb_version.tar"
update_responses_tar="$script_dir/../../$SIGNING_PROJECTNAME/$tbb_version_type/update-responses/$update_responses_tar_filename"
if test -f "$update_responses_tar"
then
  echo "$update_responses_tar_filename already exists: not running 'make $SIGNING_PROJECTNAME-update_responses-$tbb_version_type'"
else
  echo "Running 'make $SIGNING_PROJECTNAME-update_responses-$tbb_version_type'"
  pushd "$script_dir/../.." > /dev/null
  make $SIGNING_PROJECTNAME-update_responses-$tbb_version_type
  popd > /dev/null
fi

cd $update_responses_repository_dir
git checkout main
git pull --ff-only
test -n "$(git status --porcelain=v1 | grep -v '^?')" \
  && exit_error 'update_responses_repository_dir has modified files'
is_project torbrowser && cd update_3
is_project mullvadbrowser && cd update_1

rm -Rf "$tbb_version_type"
tar -xf "$update_responses_tar"
git add "$tbb_version_type"
git commit -m "$tbb_version_type: new version, $tbb_version"
git push

# we just need to push mullvadbrowser's update responses to git, not deploy to staticiforme
is_project mullvadbrowser && exit 0

update_responses_commit=$(git log -1 --format=%H)

update_dir=/srv/aus1-master.torproject.org/htdocs/torbrowser
deploy_script=$(mktemp)
trap "rm -Rf $deploy_script" EXIT
cat << EOF > "$deploy_script"
#!/bin/bash
set -e

echo "Deploying version $tbb_version"
echo "update_responses_commit: $update_responses_commit"

cd "$update_dir"
git fetch
git checkout "$update_responses_commit"

static-update-component aus1.torproject.org
EOF

chmod +x $deploy_script
scp -p $deploy_script $ssh_host_staticiforme:deploy_update_responses-$tbb_version_type.sh

echo 'To enable updates you can now run:'
echo "  ssh $ssh_host_staticiforme"
echo "  sudo -u tb-release ./deploy_update_responses-$tbb_version_type.sh"
